package com.happly.happlycloud.controller.common.interceptor;

import com.google.common.collect.Maps;
import com.happly.happlycloud.common.Const;
import com.happly.happlycloud.common.ServerResponse;
import com.happly.happlycloud.pojo.User;
import com.happly.happlycloud.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class AuthorityInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        log.info("PreHandle");
        //拿到请求在Controller中的方法名
        HandlerMethod headlerMethod = (HandlerMethod)o;
        //解析handlerMethod
        //获取请求的方法名
        String methodName = headlerMethod.getMethod().getName();
        //获取请求的类名getName包含包名和类名
        String className = headlerMethod.getBean().getClass().getSimpleName();

        //解析参数，具体的参数key以及value是什么，打印日志
        StringBuffer requestParamBuffer = new StringBuffer();
        Map paramMap = httpServletRequest.getParameterMap();
        Iterator iterator = paramMap.entrySet().iterator();

        while(iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            String mapKey = (String) entry.getKey();

            String mapValue = StringUtils.EMPTY;

            //htppServlertRequest这个参数的map，里面的value返回的是一个String[]数组
            Object obj = entry.getValue();
            if (obj instanceof String[]){
                String[] strs = (String[])obj;
                mapValue = Arrays.toString(strs);
            }
            requestParamBuffer.append(mapKey).append("=").append(mapValue);
        }
        if (StringUtils.equals(className,"UserManageController") && StringUtils.equals(methodName,"login")){
            log.info("权限拦截器拦截到请求，className:{},methodName：{}",className,methodName);
            //如果拦截到登录请求，不打印参数，防止日志泄露
            return true;
        }
        log.info("权限拦截器拦截到是，className:{},methodName：{}",className,methodName);
           // User user = null;
           //String loginToken = CookieUtil.readLoginToken(httpServletRequest);
            //if(StringUtils.isNotEmpty(loginToken)){
                //String userJsonStr = RedisShardedPoolUtil.get(loginToken);
                //String userJsonStr = (String)httpServletRequest.getAttribute(loginToken);
                //user = JsonUtil.stringToObj(userJsonStr,User.class);
             User  user = (User)httpServletRequest.getSession().getAttribute(Const.CURRENT_USER);
           // }
            if (null == user ||  Const.Role.ROLE_ADMIN != user.getRole().intValue()){
                //返回false不会调用Controller里的方法
                //不添加reset方法，会报异常 getWriter() has already been called for this response。
                httpServletResponse.reset();
                //脱离了springmvc流程，所以要设置未utf-8防止乱码
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json;charset=UTF-8");

                PrintWriter out = httpServletResponse.getWriter();
                if (null == user){
                    if (StringUtils.equals(className,"ProductManageController") && StringUtils.equals(methodName,"richtext_img_upload")) {
                        Map resultMap = Maps.newHashMap();
                        resultMap.put("success", false);
                        resultMap.put("msg", "请登录管理员");
                        out.print(JsonUtil.objToString(resultMap));
                    }else{
                            out.print(JsonUtil.objToString(ServerResponse.createByErrorMessage("拦截器拦截，用户未登录")));
                        }
                }else{
                    if (StringUtils.equals(className,"ProductManageController") && StringUtils.equals(methodName,"richtext_img_upload")) {
                        Map resultMap = Maps.newHashMap();
                        resultMap.put("success", false);
                        resultMap.put("msg", "无权限操作");
                        out.print(JsonUtil.objToString(resultMap));
                    }
                    out.print(JsonUtil.objToString(ServerResponse.createByErrorMessage("拦截器拦截，用户无权限操作")));
                }
                out.flush();
                out.close();//关掉流
                return false;
            }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("postHandleAfter");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("postHandleComplete");
    }
}
